// pages/index/shop/shop.js
const app = getApp()
import Notify from '@vant/weapp/notify/notify';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		all:[],
		onSale:[],
    mine:[],
    //收货地址
    list:[],
    user:{},
    modalName:null,
    temp:{},
    buy:1,
    index: null,
    loadModel:true
	},
	onLoad(options) {
	},
	onShow() {
    this.setData({
      user:wx.getStorageSync('user')
    })
    this.getallgoods()
    this.getAllAddress()
	},
	getallgoods(){
		//一次请求获取全部的信息，减少网络请求
		app.request({
      url: app.globalData.apiUrl + '/goods/all' ,
      method: 'GET',
    }).then(res => {
      if (res.statusCode == 200) {
        this.setData({
          all:res.data.data.all,
          onSale:res.data.data.onsale,
          mine:res.data.data.mine
        })
      } else {
        loadModel: false
        Notify('服务错误，稍后重试');
      }
    })
  },
  //跳转到新增界面
	gotoadd() {
		wx.navigateTo({
			url: '/pages/index/shop/add/add',
		})
  },
  //获取所有收货地址
  getAllAddress(){
    app.request({
      url: app.globalData.apiUrl + "/address/"+this.data.user.id,
      method: 'GET',
    }).then(res => {
      if (res.statusCode == 200) {
        this.setData({
          list:res.data.data,
          loadModel:false
        })
      } else {
        this.setData({
          loadModel:false
        })
        Notify('服务错误，稍后重试');
      }
    })
  },
  showModal(e) {
    console.log(e)
    this.setData({
      modalName: e.currentTarget.dataset.target,
      temp:e.currentTarget.dataset.item
    })
    console.log(this.data)
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      temp:null,
      buy:1,
      index:null
    })
    console.log(this.data)
  },
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  //下单
  submit(){
    var order=JSON.stringify({
      num:this.data.buy,
      gid:this.data.temp.id,
      uid:this.data.user.id,
      aid:this.data.list[this.data.index].id,
      createTime: Date.parse(new Date())
    })
    app.request({
      url: app.globalData.apiUrl + "/order/"+order,
      method: 'POST',
    }).then(res => {
      if (res.statusCode == 200) {
				Notify({
          type: 'primary',
          message: '购买成功，已生成订单'
        })
        this.getallgoods()
        this.hideModal()
      } else {
        Notify('服务错误，稍后重试');
      }
    })
  },
  gotoUpdate(e){
		var order=JSON.stringify(e.target.dataset.order)
		console.log(order)
    wx.navigateTo({
			url: '/pages/index/shop/update/update?goods='+order,
		})
	},
	delete(e){
		var id=e.target.dataset.id
		var goods=JSON.stringify({
			id:id
		})
    app.request({
      url: app.globalData.apiUrl + "/goods/"+goods,
      method: 'DELETE',
    }).then(res => {
      if (res.statusCode == 200) {
        Notify({
          type: 'primary',
          message: '删除成功'
        })
        this.getallgoods()
      } else {
        Notify('服务错误，稍后重试');
      }
    })
  },
})